package es

import (
	"gitee.com/zjlsliupei/ghelp"
	"gitee.com/zjlsliupei/ndb/config"
	"gitee.com/zjlsliupei/ndb/request"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
)

type Join struct {
	option     config.Option
	rpcName    string
	funcName   string
	arg        ghelp.MAP
	meta       ghelp.MAP
	ginContext *gin.Context
}

func NewJoin(option config.Option, rpcName string) Join {
	return Join{
		option:   option,
		rpcName:  rpcName,
		funcName: "Join",
		arg:      make(ghelp.MAP),
	}
}

// SetGroupId 不超过20位，用于数据分组
func (this *Join) SetGroupId(groupId string) *Join {
	this.arg["group_id"] = groupId
	return this
}

// SetFormId 需要获取的表单id, 必填
func (this *Join) SetFormIds(formIds []string) *Join {
	this.arg["form_ids"] = formIds
	return this
}

// SetJoin 1表示用_join_id进行关联查询，否则默认是id关联
func (this *Join) SetJoin(join int64) *Join {
	this.arg["join"] = join
	return this
}

// SetQuery 搜索条件，es语法, 必填
func (this *Join) SetQuery(query map[string]interface{}) *Join {
	this.arg["query"] = query
	return this
}

// SetSize 分页大小，默认10
func (this *Join) SetSize(size int64) *Join {
	this.arg["size"] = size
	return this
}

// SetPage 第几页，默认0
func (this *Join) SetPage(page int64) *Join {
	this.arg["page"] = page
	return this
}

// SetOrderBy 排序字段，只支持数字和日期类型，如果是创建时间用escreate_time，修改时间用esupdate_time，其他用[$field]格式转义
func (this *Join) SetOrderBy(orderby string) *Join {
	this.arg["orderby"] = orderby
	return this
}

// SetOrderAsc 1 表示按顺序排序，默认是倒序
func (this *Join) SetOrderAsc(orderasc int64) *Join {
	this.arg["orderasc"] = orderasc
	return this
}

// AutoMeta 自动设置meta，根据gin的上下文来解析，meta; 如果同时使用了Meta优先以Meta为准
func (this *Join) AutoMeta(c *gin.Context) *Join {
	_c := c.Copy()
	this.ginContext = _c
	return this
}

// SetMeta 设置meta
func (this *Join) SetMeta(meta ghelp.MAP) *Join {
	this.meta = meta
	return this
}

func (this *Join) Do() (gjson.Result, error) {
	req := request.NewRequest(this.option.Addr)
	req.FuncName(this.funcName)
	req.RpcName(this.rpcName)
	req.AutoMeta(this.ginContext)
	req.SetMeta(this.meta)
	return req.Do(this.arg)
}
